package org.util.collection;

import com.google.common.base.Function;
import com.google.common.collect.Maps;
import org.apache.commons.beanutils.BeanToPropertyValueTransformer;
import org.apache.commons.collections.CollectionUtils;
import org.util.common.ReflectUtil;

import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * Created by sinceow on 2014/6/16.
 */
public class CollectionUtil {

    /**
     * 将一个Collection<E>抽取E的某个属性 propertyName 组成新的 Collection
     * 注意: propertyName需要有Getter和Setter
     * @param collections
     * @param propertyName
     * @return
     */
    public static Collection collect(Collection collections, String propertyName){
        return CollectionUtils.collect(collections, new BeanToPropertyValueTransformer(propertyName));
    }


    /**
     * 根据一个Collection<V>转换成以V的其中一个属性K(keyName)为Key的Map<K, V>
     * @param collections
     * @param keyName
     * @param <K>
     * @param <V>
     * @return
     */
    public static <K, V> Map<K, V> map(Iterable<V> collections,final String keyName){

        Map<K, V> targetMap = Maps.uniqueIndex(collections, new Function<V, K>() {
            @Override
            public K apply(V target) {
                return ReflectUtil.getFieldValue(target, keyName);
            }
        });

        return targetMap;
    }
}
